{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3a79ef54-63e6-429f-ba9f-590b736a7f29",
   "metadata": {},
   "source": [
    "## 2.10 改变张量的形状"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "- 创建形状为(8,)的张量re1\n",
    "- 将re1的形状改变为(2,4)，得到张量re2"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8d7baa9c-93a2-42f3-a3c1-231cdb587f2d",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74ad989a-9b82-43e1-b841-e74284cd5936",
   "metadata": {},
   "source": [
    "### 3.任务分析\n",
    "\n",
    "可以使用tf.reshape方法改变张量的形状。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor([0 1 2 3 4 5 6 7], shape=(8,), dtype=int32)\n",
      "tf.Tensor(\n",
      "[[0 1 2 3]\n",
      " [4 5 6 7]], shape=(2, 4), dtype=int32)\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "# 创建形状为(8,)的张量re1\n",
    "re1=tf.range(8)\n",
    "print(re1)\n",
    "# 将rel的形状改变为(2,4),返回新的张量re2\n",
    "re2=tf.reshape(tensor=re1,shape=(2,4))\n",
    "print(re2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5a1c0eb-30ea-4439-91ff-aa6325c1f12f",
   "metadata": {},
   "source": [
    "分析：张量形状在改变前后需要保证元素个数相同，否则会引发异常。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e2d2988-ba5a-49b0-b27b-a8bc5a32602c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
